import 'package:app/api/container/index.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

///空托呼叫
class ContainerCall extends StatefulWidget {
  const ContainerCall({super.key});

  @override
  State<ContainerCall> createState() => _ContainerCallState();
}

class _ContainerCallState extends State<ContainerCall> {

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  final FocusNode _firstFocusNode = FocusNode();

  //站点码
  String _code = "";

  // 托盘数量
  String _number = "1";

  @override
  void initState() {
    super.initState();
    // 在初始化时将焦点放在第一个文本框上
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
      setParams(ModalRoute.of(context)!.settings.arguments);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _firstFocusNode.dispose();
  }

  void submit() {
    Forms.validate(_formKey!).then((valid) {
      if (valid) {
        if(!RegExp(r'^[1-9]\d*$').hasMatch(_number)){
          Error.of(context).show('托盘数量必须大于0的数字');
          return;
        }
        ContainerApi.of(context).call(_code, _number).then((res){
          if(StringUtils.isNotNull(res) && StringUtils.isNotNull(res.data)){
            Success.of(context).show("呼叫成功，请等待配送");
            clear();
          }
        });
      }
    });
  }

  void clear() {
    setState(() {
      _code = "";
      _number = "1";
    });
  }

  void scan() async{
    String? qrCode = await scanner.scan();
    setState(() => _code = qrCode.toString());
  }

  void setValue(String key, String value) {
    switch (key) {
      case '_code':
       setState(() =>  _code = value);
        break;
      case '_number':
        setState(() =>  _number = value);
        break;
      default:
        throw Exception("key error");
    }
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  /// 设置参数
  void setParams(params) {
      setState(() {
        if(StringUtils.isNotNull(params)){
          _code = params['station']??'';
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '空托呼叫'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Container(
          color: const Color.fromARGB(255, 245, 245, 245),
          child: Column(
            children: [
              Group(
                // title: '站点信息',
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                      formKey: _formKey,
                      formItem: [
                        FormItem(
                          type: 'input',
                          labelText: '站  点  码',
                          labelWidth: 90,
                          focusNode: _firstFocusNode,
                          placeholder: '请扫描站点码',
                          filedName: 'code',
                          icon: const Icon(Icons.qr_code_scanner_rounded),
                          value: _code,
                          iconOnTap: scan,
                          onChange: (value) => setValue('_code', value),
                          rules: const {
                            'code': [
                              {'required': true, 'message': '站点码不能为空'}
                            ]
                          },
                        ),
                        FormItem(
                          type: 'input',
                          labelText: '托盘数量',
                          labelWidth: 90,
                          placeholder: '请输入托盘数量',
                          filedName: 'number',
                          icon: const Icon(Icons.numbers_sharp),
                          value: _number,
                          onChange: (value) => setValue('_number', value),
                          rules: const {
                            'number': [
                              {'required': true, 'message': '托盘数量不能为空'}
                            ]
                          },
                        )
                      ],
                    ),
                    Padding(
                      padding: const EdgeInsets.only(top: 10, right: 10),
                      child: Button(
                        label: '清除',
                        icon: Icons.delete_forever,
                        onPressed: clear,
                        fontColor: Colors.black,
                        backgroundColor: Colors.white,
                        borderColor: const Color.fromARGB(255, 133, 133, 133),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(
                width: MediaQuery.of(context).size.width,
                child: Padding(
                  padding: const EdgeInsets.only(top: 50, left: 20, right: 20),
                  child: Button(
                    onPressed: submit,
                    label: '空托呼叫',
                    height: 60,
                    fontSize: 18,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}